import React, {Component} from 'react';
import {connect} from 'dva';
import {Link} from 'dva/router';
import {Form, Card, Row, Col, Input, Select, message, Table, Button, Popconfirm} from 'antd';
import styles from './QueryAdmin.less';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import AdminEdit from '../../components/AdminEdit';
import AdminSaveEdit from '../../components/AdminSaveEdit';
import {routerRedux} from 'dva/router';
import {hashHistory} from 'react-router';
import {powerControl} from '../../utils/powerControl';

const FormItem = Form.Item;
const {Option} = Select;
const AuthButton = powerControl(Button);
@connect(state => ({
    adminManage: state.adminManage,
}))
@Form.create()
export default class QueryAdmin extends Component {

    state = {
        adminList: [],
        searchValues: {},
        loading: false,
        visible: false,
    };

    handleSearch = (e) => {
        e.preventDefault();
        const {dispatch, form} = this.props;
        form.validateFields((err, fieldValue) => {
            if (err) return;
            const values = {
                ...fieldValue,
            };
            this.setState({
                searchValues: values,
            });
            dispatch({
                type: 'adminManage/queryAdminList',
                payload: values,
            });
        });
    };

    componentDidMount() {
        this.props.dispatch({
            type: 'adminManage/queryAdminList',
        })
    };

    componentWillReceiveProps(nextProps) {
        if (nextProps.adminManage.adminInfo !== undefined) {
            let arr = Object.keys(nextProps.adminManage.adminInfo).map(key => nextProps.adminManage.adminInfo[key]);//转换成数组
            this.setState({
                adminList: arr,
            })
        }
    };

    handleFormReset = () => {
        const {form, dispatch} = this.props;
        form.resetFields();
        this.setState({
            searchValues: {},
        });
        dispatch({
            type: 'adminManage/queryAdminList',
            payload: {},
        });
    };

    handleDelete = (e) => {
        const {dispatch} = this.props;
        dispatch({
            type: 'adminManage/deleteAdmin',
            payload: {
                userId: e.user_id,
            },
            callback: (response) => {
                if (response.result == 0) {
                    message.success('删除成功');
                    this.handleDeleteSuccess();
                } else {
                    message.error('删除失败');
                }
            }
        });
    };

    handleDeleteSuccess = () => {
        const {dispatch} = this.props;
        const {searchValues} = this.state;
        const {pagination} = this.props.adminManage;
        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...searchValues,
        };
        dispatch({
            type: 'adminManage/queryAdminList',
            payload: params,
        });
    };

    handleTableChange = (pagination) => {
        const {dispatch} = this.props;
        const {searchValues} = this.state;
        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...searchValues,
        };
        dispatch({
            type: 'adminManage/queryAdminList',
            payload: params,
        });
    };

    handleOptionChange = (value) => {
        const {dispatch} = this.props;
        const {searchValues} = this.state;
        const params = {
            ...searchValues,
            roleId: value,
        };
        dispatch({
            type: 'adminManage/queryAdminList',
            payload: params,
        });
    };
    columns = () => {

        const columns = [
            {
                title: '用户ID',
                dataIndex: 'user_id',
                key: 'user_id',
            }, {
                title: '用户名',
                dataIndex: 'user_name',
                key: 'user_name',
            }, {
                title: '邮箱',
                dataIndex: 'email',
                key: 'email',
            }, {
                title: '添加时间',
                dataIndex: 'add_time',
                key: 'add_time',
            }, {
                //     title: '管理员管理权限列表',
                //     dataIndex: 'action_list',
                //     key: 'action_list',
                // }, {
                title: '管理员导航栏配置项',
                dataIndex: 'nav_list',
                key: 'nav_list',
            }, {
                title: '管理员角色',
                dataIndex: 'role_id',
                key: 'role_id',
            }, {
                title: '操作',
                width:'100px',
                render: (text, record) => {
                    return (
                        <Button.Group type="ghost">
                            <Row gutter={{md: 8, lg: 24, xl: 48}}>
                                <Col md={4} sm={12}>
                                    <AuthButton size="small" auth="management.edit"><Link to={{pathname:'/management/PowerListDetails',state:{record:record}}}>详情</Link></AuthButton>
                                </Col>
                                <Col md={4} sm={12}>
                                    <Popconfirm title="确定要删除吗？" onConfirm={() => this.handleDelete(record)}>
                                        <AuthButton size="small" type="danger" auth="management.delete">删除</AuthButton>
                                    </Popconfirm>
                                </Col>
                            </Row>
                            <Row gutter={{md: 8, lg: 24, xl: 48}}>
                                <Col md={8} sm={24}>
                                    <AuthButton size="small" auth="management.syspowerconfig"><Link to={{pathname:'/management/AdminPowerSetting',state:record.user_id}}>系统权限配置</Link></AuthButton>
                                </Col>
                            </Row>

                        </Button.Group>

                    );
                }
            }
        ];
        return columns;
    };

    renderSimpleForm() {
        const {getFieldDecorator} = this.props.form;
        const {adminManage} = this.props;

        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{md: 8, lg: 24, xl: 48}}>
                    <Col md={8} sm={24}>
                        <FormItem>
                            {getFieldDecorator('userName')(<Input size="default" placeholder="管理员用户名"/>)
                            }
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem>
                            {getFieldDecorator('roleId')(<Select onChange={this.handleOptionChange} placeholder="可选择管理员角色">
                                <Option value={0}>平台管理员</Option>
                                <Option value={1}>供应商管理员</Option>
                                <Option value={2}>运营人员</Option>
                            </Select>)}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
            <span className={styles.sumbitButtons}>
              <AuthButton type="primary" htmlType="submit" auth="management.search" loading={adminManage.submitting}>查询</AuthButton>
              <AuthButton style={{marginLeft: 8}} auth="management.reset" onClick={this.handleFormReset}>重置</AuthButton>
            </span>
                    </Col>
                </Row>
            </Form>
        );
    }

    renderForm() {
        return this.renderSimpleForm();
    }

    render() {

        const {pagination} = this.props.adminManage;
        const paginationProps = {
            showSizeChanger: true,
            showQuickJumper: true,
            ...pagination,
        };
        return (
            <PageHeaderLayout title="管理员管理">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>
                            {this.renderForm()}
                        </div>
                        <div className={styles.tableListOperator}>
                            <AdminSaveEdit searchValues={this.state.searchValues}/>
                        </div>
                        <div>
                            <Table
                                columns={this.columns()}
                                dataSource={this.state.adminList}
                                rowKey={row => row.user_id}
                                pagination={paginationProps}
                                onChange={this.handleTableChange}
                                // scroll={{ x: 2000 }}
                            />
                        </div>
                    </div>
                </Card>
            </PageHeaderLayout>
        )
    }
}
